package mspbots.cw.business.core.priorities;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.cw.business.core.BaseReceiver;
import mspbots.cw.common.ResultMsg;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.Duration;

/**
 * @author Jay.Yang
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class PrioritiesReceiver extends BaseReceiver {

    private final PrioritiesRepository prioritiesRepository;

//    @RabbitListener(queues = "connect-wise.priority.tl")
    public void process(ResultMsg resultMsg) {
        Priorities data = super.objectMapper.convertValue(resultMsg.getEntity(), Priorities.class);
        data.setId(null);
        data.setCwId(resultMsg.getId());
        data.setTenantCode(resultMsg.getTenantId());
        data.setSyncTime(resultMsg.getSyncDate());

        this.prioritiesRepository.findByCwIdAndTenantCode(resultMsg.getId(), resultMsg.getTenantId())
                .map(result -> {
                    data.setId(result.getId());
                    return data;
                })
                .defaultIfEmpty(data)
                .flatMap(this.prioritiesRepository::save).block(Duration.ofSeconds(10));
    }

}
